package com.bw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bw.entity.PageResult;
import com.bw.pojo.comment.ProductReply;
import com.bw.pojo.comment.ProductReplyPages;
import com.bw.pojo.goods.Goods;
import com.bw.pojo.goods.Sku;
import com.bw.pojo.goods.Spu;
import com.bw.service.comment.ProductReplyService;
import com.bw.service.goods.CategoryService;
import com.bw.service.goods.SkuService;
import com.bw.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/item")
public class ItemController {

    @Reference
    private ProductReplyService productReplyService;
    @Reference
    private SpuService spuService;
    @Autowired
    private TemplateEngine templateEngine;
    @Reference
    private SkuService skuService;

    @Value("${pagePath}")
    private String pagePath;

    @Reference
    private CategoryService categoryService;



    @GetMapping("/findPage")
    public PageResult<ProductReply> findPage(int page, int size){
        return productReplyService.findPage(page,size);
    }

    @GetMapping("findGood")
    public ProductReplyPages findGood(int page, int size, String id){
        return productReplyService.findGoodCommentPageBySkuId(page,size,id);
    }

    @GetMapping("/testPage")
    public String testPage(Model model, String id,
                           @RequestParam(required = false,defaultValue = "1",value = "pageNum")Integer pageNum,
                           @RequestParam(defaultValue = "10",value="pageSize")Integer pageSize,
                           @RequestParam(defaultValue = "1",value="type")Integer type
                           ){

//        String userNa
        if(pageNum==null){
            pageNum=1;
        }

        if (pageNum<=0) {
            pageNum=1;
        }
        if (pageSize==null) {
            pageSize=5;
        }
        if (type==null) {
            type=1;
        }
        ProductReplyPages productReplyPages = null;
        switch(type){
            case 2:
                productReplyPages = productReplyService.findHasPicPageBySkuId(pageNum,pageSize,id);
                break;
            case 3:
                productReplyPages = productReplyService.findHasReplyPageBySkuId(pageNum,pageSize,id);
                break;
            case 4:
                productReplyPages = productReplyService.findGoodCommentPageBySkuId(pageNum,pageSize,id);
                break;
            case 5:
                productReplyPages = productReplyService.findMiddleCommentPageBySkuId(pageNum,pageSize,id);
                break;
            case 6:
                productReplyPages = productReplyService.findBadCommentPageBySkuId(pageNum,pageSize,id);
                break;
            default:
                productReplyPages = productReplyService.findAllPageBySkuId(pageNum,pageSize,id);
        }

        model.addAttribute("sta",productReplyPages.getSatisfaction()*20);
        model.addAttribute("commentCount",productReplyPages.getProductReplyPageInfo().getTotal());
        model.addAttribute("pageInfo",productReplyPages.getProductReplyPageInfo());
        model.addAttribute("skuId",id);
        model.addAttribute("type",type);
        return "item1";

    }

    /**
     * 生成端口详情页
     */
    @GetMapping("/createPage")
    public  String createPage(Model dataModel,String id,
                              @RequestParam(required = false,defaultValue = "1",value = "pageNum")Integer pageNum,
                              @RequestParam(defaultValue = "10",value="pageSize")Integer pageSize,
                              @RequestParam(defaultValue = "1",value="type")Integer type) {

        if(pageNum==null){
            pageNum=1;
        }

        if (pageNum<=0) {
            pageNum=1;
        }
        if (pageSize==null) {
            pageSize=5;
        }
        if (type==null) {
            type=1;
        }
        ProductReplyPages productReplyPages = null;
        switch(type){
            case 2:
                productReplyPages = productReplyService.findHasPicPageBySkuId(pageNum,pageSize,id);
                break;
            case 3:
                productReplyPages = productReplyService.findHasReplyPageBySkuId(pageNum,pageSize,id);
                break;
            case 4:
                productReplyPages = productReplyService.findGoodCommentPageBySkuId(pageNum,pageSize,id);
                break;
            case 5:
                productReplyPages = productReplyService.findMiddleCommentPageBySkuId(pageNum,pageSize,id);
                break;
            case 6:
                productReplyPages = productReplyService.findBadCommentPageBySkuId(pageNum,pageSize,id);
                break;
            default:
                productReplyPages = productReplyService.findAllPageBySkuId(pageNum,pageSize,id);
        }

        if (productReplyPages.getSatisfaction()!=null) {
            dataModel.addAttribute("sta",productReplyPages.getSatisfaction()*20);
        } else {
            dataModel.addAttribute("sta","暂无评价");
        }
        dataModel.addAttribute("commentCount",productReplyPages.getProductReplyPageInfo().getTotal());
        dataModel.addAttribute("pageInfo",productReplyPages.getProductReplyPageInfo());
        dataModel.addAttribute("skuId",id);
        dataModel.addAttribute("type",type);


        Integer[] commentCount = productReplyService.getCommentCount(id);
        dataModel.addAttribute("allCounts",commentCount[0]);
        dataModel.addAttribute("hasPicCounts",commentCount[1]);
        dataModel.addAttribute("hasReplyCounts",commentCount[2]);
        dataModel.addAttribute("goodCounts",commentCount[3]);
        dataModel.addAttribute("middleCounts",commentCount[4]);
        dataModel.addAttribute("badCounts",commentCount[5]);

        Sku skuTemp = skuService.findById(id);
        //查询商品信息
        Goods goods = spuService.findGoodsById(skuTemp.getSpuId());
        //获取spu信息
        Spu spu = goods.getSpu();
        //查询商品分类数据
        List<String> categoryList = new ArrayList<String>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级分类
        //获取sku列表
        List<Sku> skuList = goods.getSkuList();
        //生成sku地址列表
        Map urlMap = new HashMap();
        for (Sku sku : skuList) {
            //对规格JSON字符串进行排序
            String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
            urlMap.put(specJson, sku.getId() + ".html");
        }
        for (Sku sku : skuList) {
            if (!skuTemp.getId().equals(sku.getId()))
            {
                continue;
            }
            //1上下文
//            Context context = new Context();
            //创建数据模型
//            Map<String ,Object> dataModel = new HashMap();
            dataModel.addAttribute("spu", spu);
            dataModel.addAttribute("sku", sku);
            dataModel.addAttribute("categoryList", categoryList);//商品分类
            //商品图片查询
            dataModel.addAttribute("skuImages", sku.getImages().split(","));//SKU图片列表
            dataModel.addAttribute("spuImages", spu.getImages().split(","));//SPU图片列表
            //商品的显示规格和参数列表
            Map paraItems = JSON.parseObject(spu.getParaItems());//spu参数列表
            dataModel.addAttribute("paraItems", paraItems);
            Map specItems = JSON.parseObject(sku.getSpec());//当前SKU的规格
            dataModel.addAttribute("specItems", specItems);
            //选中处理
            Map<String, List> specMap = (Map) JSON.parse(spu.getSpecItems());
            for (String key : specMap.keySet()) {
                List<String> list = specMap.get(key);
                List<Map> maplist = new ArrayList<>();
                for (String value : list) {
                    Map map = new HashMap();
                    map.put("option", value);
                    if ((specItems.get(key) + "").equals(value)) {
                        map.put("checked", true);
                    } else {
                        map.put("checked", false);
                    }
                    //创建页面
                    Map<String, String> spec = (Map) JSON.parseObject(sku.getSpec());//当前的Sku
                    spec.put(key, value);
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url", urlMap.get(specJson));
                    maplist.add(map);
                }
                specMap.put(key, maplist);//新结构集覆盖原来集合
            }
            dataModel.addAttribute("specMap", specMap);//规格面板
        }


        return "item";
    }




}
